'use strict'
//连接数据库
var mysql = require('mysql');
var conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'liu0769777',
    database: 'spider'
});


exports.count = function(infohash, callback) {

    //var conn = connect();
    //查询
    var sql = 'select count(1) rn from t_btchina where ? ';
    conn.query(sql, {
        infohash: infohash
    }, function(err, rows, fields) {
        if (err) {
            callback(true);
        } else {
            callback(rows[0].rn > 0);
        }
        //conn.end();
    });

};

exports.save = function(data) {
    //var conn = connect();
    //查询
    var sql = 'INSERT INTO t_btchina SET ? ';
    conn.query(sql, data, function(err, rows, fields) {
        if (err) {
            conn.rollback(function() {});
            if (err.code != 'ER_DUP_ENTRY') {
                console.log("save faild :" + err);
            }
        } else {
            conn.commit(function() {
                console.log("Successful insert!");
            });
        }
        //conn.end();
    });
};

exports.increase = function(infohash) {
    //var conn = connect();
    //查询
    var sql = 'update t_btchina SET vcount=vcount+1,modifyTime=now() where ? ';
    conn.query(sql, { infohash: infohash },
        function(err, rows, fields) {
            if (!err) {
                conn.commit(function() {
                    console.log(infohash + " +1");
                });
            } else {
                conn.rollback(function() {});
                console.log("increase There was an error with MySQL.");
            }
            // conn.end();
        });
};